package br.com.ime.usp.cmep;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.AbstractAction;
import com.markupartist.android.widget.ActionBar.IntentAction;

import br.com.ime.usp.cmep.BandexUtils.BandexAccessor;
import br.com.ime.usp.cmep.BandexUtils.BandexNetworkAccessor;
import br.com.ime.usp.cmep.BandexUtils.BandexComment;
import br.com.ime.usp.cmep.BandexUtils.BandexStatus;
import br.com.ime.usp.cmep.CardapioActivity.BandexStatusListAdapter;
import br.com.ime.usp.cmep.RatingActivity.BandexCommentListAdapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.DataSetObserver;
import android.opengl.Visibility;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Comparator;

public class ReadCardapioActivity extends Activity {
	
	private String bandex;
	private double media, desvio, amostras, erro, confianca, precisao;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cardapio_read);
		
		// configura actionbar
        final ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
        actionBar.setTitle(getString(R.string.cardapio_titulo));
        actionBar.setHomeAction(new HomeAction(this));        
        actionBar.addAction(new BackAction(this));
		
		// dados do bandex...
		Bundle b = getIntent().getExtras();
		bandex = b.getString("bandex");
		media = b.getDouble("media");
		desvio = b.getDouble("desvio");
		amostras = b.getDouble("amostras");
		erro = b.getDouble("erro");
		confianca = b.getDouble("confianca");
		precisao = b.getDouble("precisao");
		
		TextView title = (TextView) findViewById(R.id.cardapio_read_bandex);
		if(title != null)
			title.setText(bandex);
		
		TextView text = (TextView) findViewById(R.id.cardapio_read_texto);
		if(text != null)
			text.setText("");
		
		new DownloadCardapioTask().execute(bandex);
	}
	
	void escreverCardapio(String dados) {
		TextView text = (TextView) findViewById(R.id.cardapio_read_texto);
		if(text != null)
			text.setText(dados);
	}
	
	
	// ----------- AsyncTask ------------
	
	private class DownloadCardapioTask extends AsyncTask<String, Void, String> {
		private String error = "";
		
		/** The system calls this to perform work in a worker thread and
	      * delivers it the parameters given to AsyncTask.execute() */
	    protected String doInBackground(String... params) {
	    	try {
	    		String bandex = params[0];
	    		return (new BandexNetworkAccessor()).getCardapio(bandex);
	    	}
	    	catch(Exception e){
	    		error = e.getMessage();
	    		return "Erro";
	    	}
	    }
	    
	    /** The system calls this to perform work in the UI thread and delivers
	      * the result from doInBackground() */
	    protected void onPostExecute(String result) {
	    	if(error.equals(""))
	    		goBack(result);
	    	else
	    		goBackError(error);
	    }
	}
	
	protected void goBack(String data) {
		// tira a bolinha
		final ProgressBar loading = (ProgressBar) findViewById(R.id.cardapio_read_loading);
		((LinearLayout)loading.getParent()).removeView(loading);
		
		// popula o textview
		escreverCardapio(data);
	}
	
	protected void goBackError(String error) {
		Toast.makeText(getApplicationContext(), error, Toast.LENGTH_SHORT).show();
		
		// tira a bolinha
		final ProgressBar loading = (ProgressBar) findViewById(R.id.cardapio_read_loading);
		((LinearLayout)loading.getParent()).removeView(loading);
	}
	
	
	
	// --------- coisas da actionbar ---------------
	
	// volta para a tela anterior
    private class BackAction extends AbstractAction {
    	private Activity act;
        public BackAction(Activity a) {
            super(R.drawable.ic_action_back); act = a;
        }
        public void performAction(View view) {
            act.finish();
        }
    }
    
    // volta pra home
    private class HomeAction extends AbstractAction {
    	private Activity act;
        public HomeAction(Activity a) {
            super(R.drawable.ic_launcher); act = a;
        }
        public void performAction(View view) {
        	Intent i = new Intent(act, CMEPActivity.class);
        	act.startActivity(i);
        	act.finish();
        }
    }

}
